
/* Generated by Interface Builder */

#import "Random.h"
#import <stdio.h>
#import <libc.h>
#import <appkit/nextstd.h>
#import <appkit/Control.h>
#import <appkit/Form.h>
#import <appkit/Text.h>
#import <appkit/Matrix.h>
#import <appkit/ScrollView.h>
#import <appkit/Application.h>
extern void srandom();
extern int random();

@implementation Random

+new {
int i;
	self = [super new];
	[self initialize];
	return self;
}

-initialize {
int i;
id tmp_id;
    [self stop:self];
	total = 0;
	average = 0.0;
	numGen = 0;
    [numGenForm setIntValue:numGen];        
    [averageForm setFloatValue:average];
	for (i=0; i<100; i++) {
		numbers[i] = 0;
    	tmp_id = [textMatrix findCellWithTag:i];
	    [tmp_id setStringValue:"0"];
	}
	srandom(time(0));
	scrollText = [scrollView docView];
    [scrollText setText:""];
	numberText[0] = '\0';
}

- setNumGenForm:anObject
{
    numGenForm = anObject;
    return self;
}

- setAverageForm:anObject
{
    averageForm = anObject;
    return self;
}

- setTextMatrix:anObject
{
    textMatrix = anObject;
    return self;
}

- setScrollView:anObject
{
    scrollView = anObject;
    return self;
}

void update (teNum, now, myself)
DPSTimedEntry teNum;
double now;
id myself;
{
    [myself doTimedEntry];        
}

- doTimedEntry
{
char string[5];
static id this_text;
	newNumber = (random() % 100) + 1;  /* random number from 1 to 100 */
	numGen += 1;
	if (numGen > MAX_COUNT)
		[self stop:self];
	total += newNumber;
	numbers[newNumber]++;
	average = (float) total / (float) numGen;
    [numGenForm setIntValue:numGen];        
    [averageForm setFloatValue:average];
    this_text = [textMatrix findCellWithTag:newNumber];
    sprintf(string, "%d", numbers[newNumber]);
    [this_text setStringValue:string];
    sprintf(string, "%d\n", newNumber);
    strcat(numberText, string);
    [scrollText setText:numberText];

}

// Good programming practice. Free what you create!
- free
{
    [self stop:self];
    return [super free];
}



- start:sender
{
	if (!running) {
		running = 1;
    	clockTE = DPSAddTimedEntry(0.0, &update, self, NX_MODALRESPTHRESHOLD);
	}
    return self;
}

- stop:sender
{
	if (running) {
		running = 0;
    	DPSRemoveTimedEntry (clockTE);
	}
    return self;
}


- reset:sender
{
	[self initialize];
	return self;
}

@end
